<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
	<title>实现右键菜单</title>
	<style>
		#rightClickMenu {
			display: none;
			position: absolute;
			background-color: #FFFFFF;
			border: 1px solid #000000;
			padding: 5px;
			z-index: 65535;
		}
 
		#rightClickMenu li {
			list-style: none;
			cursor: pointer;
		}
 
		#rightClickMenu li:hover {
			background-color: red;
			color: white;
		}
	</style>
	<script type="text/javascript">
	function init() {
		var rightClickMenu = document.getElementById('rightClickMenu');
		document.getElementById('rightClickArea').addEventListener('contextmenu', function(rightClickArea) {
			// 不显示浏览器自带的右键菜单：
			rightClickArea.preventDefault();
			// 设置右键菜单的坐标位置：
			rightClickMenu.style.left = rightClickArea.pageX + 'px';
			rightClickMenu.style.top  = rightClickArea.pageY + 'px';
			// 显示右键菜单：
			rightClickMenu.style.display = 'block';
			// 失焦后隐藏右键菜单
			document.addEventListener('click', function() {
					rightClickMenu.style.display = 'none';
			}, {
				once: true
			});
		});
	    // 右键菜单失焦后，二级菜单也要隐藏：  
		document.querySelector('#rightClickMenu').addEventListener('mouseleave', function(e) {
			var relatedTarget = e.relatedTarget;
			if (!rightClickMenu.contains(relatedTarget)) {
				rightClickMenu.style.display = 'none';
			}
		});
	}
	</script>
</head>
 
<body onload="init();">
 
	<div id="rightClickArea" style="width:100%;height:100%;overflow-y:hidden;">
		这是右键点击区域。
	</div>
 
	<ul id="rightClickMenu">
		<li>===菜单项111===</li>
		<li>===菜单项222===</li>
		<li>===菜单项333===</li>
	</ul>
 
</body>
 
</html>